home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / SocketServer.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  23KB  |  712 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Generic socket server classes.
  5.  
  6. This module tries to capture the various aspects of defining a server:
  7.  
  8. For socket-based servers:
  9.  
  10. - address family:
  11.         - AF_INET{,6}: IP (Internet Protocol) sockets (default)
  12.         - AF_UNIX: Unix domain sockets
  13.         - others, e.g. AF_DECNET are conceivable (see <socket.h>
  14. - socket type:
  15.         - SOCK_STREAM (reliable stream, e.g. TCP)
  16.         - SOCK_DGRAM (datagrams, e.g. UDP)
  17.  
  18. For request-based servers (including socket-based):
  19.  
  20. - client address verification before further looking at the request
  21.         (This is actually a hook for any processing that needs to look
  22.          at the request before anything else, e.g. logging)
  23. - how to handle multiple requests:
  24.         - synchronous (one request is handled at a time)
  25.         - forking (each request is handled by a new process)
  26.         - threading (each request is handled by a new thread)
  27.  
  28. The classes in this module favor the server type that is simplest to
  29. write: a synchronous TCP/IP server.  This is bad class design, but
  30. save some typing.  (There\'s also the issue that a deep class hierarchy
  31. slows down method lookups.)
  32.  
  33. There are five classes in an inheritance diagram, four of which represent
  34. synchronous servers of four types:
  35.  
  36.         +------------+
  37.         | BaseServer |
  38.         +------------+
  39.               |
  40.               v
  41.         +-----------+        +------------------+
  42.         | TCPServer |------->| UnixStreamServer |
  43.         +-----------+        +------------------+
  44.               |
  45.               v
  46.         +-----------+        +--------------------+
  47.         | UDPServer |------->| UnixDatagramServer |
  48.         +-----------+        +--------------------+
  49.  
  50. Note that UnixDatagramServer derives from UDPServer, not from
  51. UnixStreamServer -- the only difference between an IP and a Unix
  52. stream server is the address family, which is simply repeated in both
  53. unix server classes.
  54.  
  55. Forking and threading versions of each type of server can be created
  56. using the ForkingMixIn and ThreadingMixIn mix-in classes.  For
  57. instance, a threading UDP server class is created as follows:
  58.  
  59.         class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
  60.  
  61. The Mix-in class must come first, since it overrides a method defined
  62. in UDPServer! Setting the various member variables also changes
  63. the behavior of the underlying server mechanism.
  64.  
  65. To implement a service, you must derive a class from
  66. BaseRequestHandler and redefine its handle() method.  You can then run
  67. various versions of the service by combining one of the server classes
  68. with your request handler class.
  69.  
  70. The request handler class must be different for datagram or stream
  71. services.  This can be hidden by using the request handler
  72. subclasses StreamRequestHandler or DatagramRequestHandler.
  73.  
  74. Of course, you still have to use your head!
  75.  
  76. For instance, it makes no sense to use a forking server if the service
  77. contains state in memory that can be modified by requests (since the
  78. modifications in the child process would never reach the initial state
  79. kept in the parent process and passed to each child).  In this case,
  80. you can use a threading server, but you will probably have to use
  81. locks to avoid two requests that come in nearly simultaneous to apply
  82. conflicting changes to the server state.
  83.  
  84. On the other hand, if you are building e.g. an HTTP server, where all
  85. data is stored externally (e.g. in the file system), a synchronous
  86. class will essentially render the service "deaf" while one request is
  87. being handled -- which may be for a very long time if a client is slow
  88. to reqd all the data it has requested.  Here a threading or forking
  89. server is appropriate.
  90.  
  91. In some cases, it may be appropriate to process part of a request
  92. synchronously, but to finish processing in a forked child depending on
  93. the request data.  This can be implemented by using a synchronous
  94. server and doing an explicit fork in the request handler class
  95. handle() method.
  96.  
  97. Another approach to handling multiple simultaneous requests in an
  98. environment that supports neither threads nor fork (or where these are
  99. too expensive or inappropriate for the service) is to maintain an
  100. explicit table of partially finished requests and to use select() to
  101. decide which request to work on next (or whether to handle a new
  102. incoming request).  This is particularly important for stream services
  103. where each client can potentially be connected for a long time (if
  104. threads or subprocesses cannot be used).
  105.  
  106. Future work:
  107. - Standard classes for Sun RPC (which uses either UDP or TCP)
  108. - Standard mix-in classes to implement various authentication
  109.   and encryption schemes
  110. - Standard framework for select-based multiplexing
  111.  
  112. XXX Open problems:
  113. - What to do with out-of-band data?
  114.  
  115. BaseServer:
  116. - split generic "request" functionality out into BaseServer class.
  117.   Copyright (C) 2000  Luke Kenneth Casson Leighton <lkcl@samba.org>
  118.  
  119.   example: read entries from a SQL database (requires overriding
  120.   get_request() to return a table entry from the database).
  121.   entry is processed by a RequestHandlerClass.
  122.  
  123. '''
  124. __version__ = '0.4'
  125. import socket
  126. import select
  127. import sys
  128. import os
  129.  
  130. try:
  131.     import threading
  132. except ImportError:
  133.     import dummy_threading as threading
  134.  
  135. __all__ = [
  136.     'TCPServer',
  137.     'UDPServer',
  138.     'ForkingUDPServer',
  139.     'ForkingTCPServer',
  140.     'ThreadingUDPServer',
  141.     'ThreadingTCPServer',
  142.     'BaseRequestHandler',
  143.     'StreamRequestHandler',
  144.     'DatagramRequestHandler',
  145.     'ThreadingMixIn',
  146.     'ForkingMixIn']
  147. if hasattr(socket, 'AF_UNIX'):
  148.     __all__.extend([
  149.         'UnixStreamServer',
  150.         'UnixDatagramServer',
  151.         'ThreadingUnixStreamServer',
  152.         'ThreadingUnixDatagramServer'])
  153.  
  154.  
  155. class BaseServer:
  156.     '''Base class for server classes.
  157.  
  158.     Methods for the caller:
  159.  
  160.     - __init__(server_address, RequestHandlerClass)
  161.     - serve_forever(poll_interval=0.5)
  162.     - shutdown()
  163.     - handle_request()  # if you do not use serve_forever()
  164.     - fileno() -> int   # for select()
  165.  
  166.     Methods that may be overridden:
  167.  
  168.     - server_bind()
  169.     - server_activate()
  170.     - get_request() -> request, client_address
  171.     - handle_timeout()
  172.     - verify_request(request, client_address)
  173.     - server_close()
  174.     - process_request(request, client_address)
  175.     - close_request(request)
  176.     - handle_error()
  177.  
  178.     Methods for derived classes:
  179.  
  180.     - finish_request(request, client_address)
  181.  
  182.     Class variables that may be overridden by derived classes or
  183.     instances:
  184.  
  185.     - timeout
  186.     - address_family
  187.     - socket_type
  188.     - allow_reuse_address
  189.  
  190.     Instance variables:
  191.  
  192.     - RequestHandlerClass
  193.     - socket
  194.  
  195.     '''
  196.     timeout = None
  197.     
  198.     def __init__(self, server_address, RequestHandlerClass):
  199.         '''Constructor.  May be extended, do not override.'''
  200.         self.server_address = server_address
  201.         self.RequestHandlerClass = RequestHandlerClass
  202.         self._BaseServer__is_shut_down = threading.Event()
  203.         self._BaseServer__serving = False
  204.  
  205.     
  206.     def server_activate(self):
  207.         '''Called by constructor to activate the server.
  208.  
  209.         May be overridden.
  210.  
  211.         '''
  212.         pass
  213.  
  214.     
  215.     def serve_forever(self, poll_interval = 0.5):
  216.         '''Handle one request at a time until shutdown.
  217.  
  218.         Polls for shutdown every poll_interval seconds. Ignores
  219.         self.timeout. If you need to do periodic tasks, do them in
  220.         another thread.
  221.         '''
  222.         self._BaseServer__serving = True
  223.         self._BaseServer__is_shut_down.clear()
  224.         while self._BaseServer__serving:
  225.             (r, w, e) = select.select([
  226.                 self], [], [], poll_interval)
  227.             if r:
  228.                 self._handle_request_noblock()
  229.                 continue
  230.         self._BaseServer__is_shut_down.set()
  231.  
  232.     
  233.     def shutdown(self):
  234.         '''Stops the serve_forever loop.
  235.  
  236.         Blocks until the loop has finished. This must be called while
  237.         serve_forever() is running in another thread, or it will
  238.         deadlock.
  239.         '''
  240.         self._BaseServer__serving = False
  241.         self._BaseServer__is_shut_down.wait()
  242.  
  243.     
  244.     def handle_request(self):
  245.         '''Handle one request, possibly blocking.
  246.  
  247.         Respects self.timeout.
  248.         '''
  249.         timeout = self.socket.gettimeout()
  250.         if timeout is None:
  251.             timeout = self.timeout
  252.         elif self.timeout is not None:
  253.             timeout = min(timeout, self.timeout)
  254.         
  255.         fd_sets = select.select([
  256.             self], [], [], timeout)
  257.         if not fd_sets[0]:
  258.             self.handle_timeout()
  259.             return None
  260.         self._handle_request_noblock()
  261.  
  262.     
  263.     def _handle_request_noblock(self):
  264.         '''Handle one request, without blocking.
  265.  
  266.         I assume that select.select has returned that the socket is
  267.         readable before this function was called, so there should be
  268.         no risk of blocking in get_request().
  269.         '''
  270.         
  271.         try:
  272.             (request, client_address) = self.get_request()
  273.         except socket.error:
  274.             return None
  275.  
  276.         if self.verify_request(request, client_address):
  277.             
  278.             try:
  279.                 self.process_request(request, client_address)
  280.             self.handle_error(request, client_address)
  281.             self.close_request(request)
  282.  
  283.         
  284.  
  285.     
  286.     def handle_timeout(self):
  287.         '''Called if no new request arrives within self.timeout.
  288.  
  289.         Overridden by ForkingMixIn.
  290.         '''
  291.         pass
  292.  
  293.     
  294.     def verify_request(self, request, client_address):
  295.         '''Verify the request.  May be overridden.
  296.  
  297.         Return True if we should proceed with this request.
  298.  
  299.         '''
  300.         return True
  301.  
  302.     
  303.     def process_request(self, request, client_address):
  304.         '''Call finish_request.
  305.  
  306.         Overridden by ForkingMixIn and ThreadingMixIn.
  307.  
  308.         '''
  309.         self.finish_request(request, client_address)
  310.         self.close_request(request)
  311.  
  312.     
  313.     def server_close(self):
  314.         '''Called to clean-up the server.
  315.  
  316.         May be overridden.
  317.  
  318.         '''
  319.         pass
  320.  
  321.     
  322.     def finish_request(self, request, client_address):
  323.         '''Finish one request by instantiating RequestHandlerClass.'''
  324.         self.RequestHandlerClass(request, client_address, self)
  325.  
  326.     
  327.     def close_request(self, request):
  328.         '''Called to clean up an individual request.'''
  329.         pass
  330.  
  331.     
  332.     def handle_error(self, request, client_address):
  333.         '''Handle an error gracefully.  May be overridden.
  334.  
  335.         The default is to print a traceback and continue.
  336.  
  337.         '''
  338.         print '-' * 40
  339.         print 'Exception happened during processing of request from', client_address
  340.         import traceback as traceback
  341.         traceback.print_exc()
  342.         print '-' * 40
  343.  
  344.  
  345.  
  346. class TCPServer(BaseServer):
  347.     """Base class for various socket-based server classes.
  348.  
  349.     Defaults to synchronous IP stream (i.e., TCP).
  350.  
  351.     Methods for the caller:
  352.  
  353.     - __init__(server_address, RequestHandlerClass, bind_and_activate=True)
  354.     - serve_forever(poll_interval=0.5)
  355.     - shutdown()
  356.     - handle_request()  # if you don't use serve_forever()
  357.     - fileno() -> int   # for select()
  358.  
  359.     Methods that may be overridden:
  360.  
  361.     - server_bind()
  362.     - server_activate()
  363.     - get_request() -> request, client_address
  364.     - handle_timeout()
  365.     - verify_request(request, client_address)
  366.     - process_request(request, client_address)
  367.     - close_request(request)
  368.     - handle_error()
  369.  
  370.     Methods for derived classes:
  371.  
  372.     - finish_request(request, client_address)
  373.  
  374.     Class variables that may be overridden by derived classes or
  375.     instances:
  376.  
  377.     - timeout
  378.     - address_family
  379.     - socket_type
  380.     - request_queue_size (only for stream sockets)
  381.     - allow_reuse_address
  382.  
  383.     Instance variables:
  384.  
  385.     - server_address
  386.     - RequestHandlerClass
  387.     - socket
  388.  
  389.     """
  390.     address_family = socket.AF_INET
  391.     socket_type = socket.SOCK_STREAM
  392.     request_queue_size = 5
  393.     allow_reuse_address = False
  394.     
  395.     def __init__(self, server_address, RequestHandlerClass, bind_and_activate = True):
  396.         '''Constructor.  May be extended, do not override.'''
  397.         BaseServer.__init__(self, server_address, RequestHandlerClass)
  398.         self.socket = socket.socket(self.address_family, self.socket_type)
  399.         if bind_and_activate:
  400.             self.server_bind()
  401.             self.server_activate()
  402.         
  403.  
  404.     
  405.     def server_bind(self):
  406.         '''Called by constructor to bind the socket.
  407.  
  408.         May be overridden.
  409.  
  410.         '''
  411.         if self.allow_reuse_address:
  412.             self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  413.         
  414.         self.socket.bind(self.server_address)
  415.         self.server_address = self.socket.getsockname()
  416.  
  417.     
  418.     def server_activate(self):
  419.         '''Called by constructor to activate the server.
  420.  
  421.         May be overridden.
  422.  
  423.         '''
  424.         self.socket.listen(self.request_queue_size)
  425.  
  426.     
  427.     def server_close(self):
  428.         '''Called to clean-up the server.
  429.  
  430.         May be overridden.
  431.  
  432.         '''
  433.         self.socket.close()
  434.  
  435.     
  436.     def fileno(self):
  437.         '''Return socket file number.
  438.  
  439.         Interface required by select().
  440.  
  441.         '''
  442.         return self.socket.fileno()
  443.  
  444.     
  445.     def get_request(self):
  446.         '''Get the request and client address from the socket.
  447.  
  448.         May be overridden.
  449.  
  450.         '''
  451.         return self.socket.accept()
  452.  
  453.     
  454.     def close_request(self, request):
  455.         '''Called to clean up an individual request.'''
  456.         request.close()
  457.  
  458.  
  459.  
  460. class UDPServer(TCPServer):
  461.     '''UDP server class.'''
  462.     allow_reuse_address = False
  463.     socket_type = socket.SOCK_DGRAM
  464.     max_packet_size = 8192
  465.     
  466.     def get_request(self):
  467.         (data, client_addr) = self.socket.recvfrom(self.max_packet_size)
  468.         return ((data, self.socket), client_addr)
  469.  
  470.     
  471.     def server_activate(self):
  472.         pass
  473.  
  474.     
  475.     def close_request(self, request):
  476.         pass
  477.  
  478.  
  479.  
  480. class ForkingMixIn:
  481.     '''Mix-in class to handle each request in a new process.'''
  482.     timeout = 300
  483.     active_children = None
  484.     max_children = 40
  485.     
  486.     def collect_children(self):
  487.         '''Internal routine to wait for children that have exited.'''
  488.         if self.active_children is None:
  489.             return None
  490.         while len(self.active_children) >= self.max_children:
  491.             
  492.             try:
  493.                 (pid, status) = os.waitpid(0, 0)
  494.             except os.error:
  495.                 self.active_children is None
  496.                 self.active_children is None
  497.                 pid = None
  498.             except:
  499.                 self.active_children is None
  500.  
  501.             if pid not in self.active_children:
  502.                 continue
  503.             
  504.             self.active_children.remove(pid)
  505.         for child in self.active_children:
  506.             
  507.             try:
  508.                 (pid, status) = os.waitpid(child, os.WNOHANG)
  509.             except os.error:
  510.                 pid = None
  511.  
  512.             if not pid:
  513.                 continue
  514.             
  515.             
  516.             try:
  517.                 self.active_children.remove(pid)
  518.             continue
  519.             except ValueError:
  520.                 e = None
  521.                 raise ValueError('%s. x=%d and list=%r' % (e.message, pid, self.active_children))
  522.                 continue
  523.             
  524.  
  525.         
  526.  
  527.     
  528.     def handle_timeout(self):
  529.         '''Wait for zombies after self.timeout seconds of inactivity.
  530.  
  531.         May be extended, do not override.
  532.         '''
  533.         self.collect_children()
  534.  
  535.     
  536.     def process_request(self, request, client_address):
  537.         '''Fork a new subprocess to process the request.'''
  538.         self.collect_children()
  539.         pid = os.fork()
  540.         if pid:
  541.             if self.active_children is None:
  542.                 self.active_children = []
  543.             
  544.             self.active_children.append(pid)
  545.             self.close_request(request)
  546.             return None
  547.         
  548.         try:
  549.             self.finish_request(request, client_address)
  550.             os._exit(0)
  551.         except:
  552.             pid
  553.             
  554.             try:
  555.                 self.handle_error(request, client_address)
  556.             finally:
  557.                 os._exit(1)
  558.  
  559.  
  560.  
  561.  
  562.  
  563. class ThreadingMixIn:
  564.     '''Mix-in class to handle each request in a new thread.'''
  565.     daemon_threads = False
  566.     
  567.     def process_request_thread(self, request, client_address):
  568.         '''Same as in BaseServer but as a thread.
  569.  
  570.         In addition, exception handling is done here.
  571.  
  572.         '''
  573.         
  574.         try:
  575.             self.finish_request(request, client_address)
  576.             self.close_request(request)
  577.         except:
  578.             self.handle_error(request, client_address)
  579.             self.close_request(request)
  580.  
  581.  
  582.     
  583.     def process_request(self, request, client_address):
  584.         '''Start a new thread to process the request.'''
  585.         t = threading.Thread(target = self.process_request_thread, args = (request, client_address))
  586.         if self.daemon_threads:
  587.             t.setDaemon(1)
  588.         
  589.         t.start()
  590.  
  591.  
  592.  
  593. class ForkingUDPServer(ForkingMixIn, UDPServer):
  594.     pass
  595.  
  596.  
  597. class ForkingTCPServer(ForkingMixIn, TCPServer):
  598.     pass
  599.  
  600.  
  601. class ThreadingUDPServer(ThreadingMixIn, UDPServer):
  602.     pass
  603.  
  604.  
  605. class ThreadingTCPServer(ThreadingMixIn, TCPServer):
  606.     pass
  607.  
  608. if hasattr(socket, 'AF_UNIX'):
  609.     
  610.     class UnixStreamServer(TCPServer):
  611.         address_family = socket.AF_UNIX
  612.  
  613.     
  614.     class UnixDatagramServer(UDPServer):
  615.         address_family = socket.AF_UNIX
  616.  
  617.     
  618.     class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer):
  619.         pass
  620.  
  621.     
  622.     class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer):
  623.         pass
  624.  
  625.  
  626.  
  627. class BaseRequestHandler:
  628.     '''Base class for request handler classes.
  629.  
  630.     This class is instantiated for each request to be handled.  The
  631.     constructor sets the instance variables request, client_address
  632.     and server, and then calls the handle() method.  To implement a
  633.     specific service, all you need to do is to derive a class which
  634.     defines a handle() method.
  635.  
  636.     The handle() method can find the request as self.request, the
  637.     client address as self.client_address, and the server (in case it
  638.     needs access to per-server information) as self.server.  Since a
  639.     separate instance is created for each request, the handle() method
  640.     can define arbitrary other instance variariables.
  641.  
  642.     '''
  643.     
  644.     def __init__(self, request, client_address, server):
  645.         self.request = request
  646.         self.client_address = client_address
  647.         self.server = server
  648.         
  649.         try:
  650.             self.setup()
  651.             self.handle()
  652.             self.finish()
  653.         finally:
  654.             sys.exc_traceback = None
  655.  
  656.  
  657.     
  658.     def setup(self):
  659.         pass
  660.  
  661.     
  662.     def handle(self):
  663.         pass
  664.  
  665.     
  666.     def finish(self):
  667.         pass
  668.  
  669.  
  670.  
  671. class StreamRequestHandler(BaseRequestHandler):
  672.     '''Define self.rfile and self.wfile for stream sockets.'''
  673.     rbufsize = -1
  674.     wbufsize = 0
  675.     
  676.     def setup(self):
  677.         self.connection = self.request
  678.         self.rfile = self.connection.makefile('rb', self.rbufsize)
  679.         self.wfile = self.connection.makefile('wb', self.wbufsize)
  680.  
  681.     
  682.     def finish(self):
  683.         if not self.wfile.closed:
  684.             self.wfile.flush()
  685.         
  686.         self.wfile.close()
  687.         self.rfile.close()
  688.  
  689.  
  690.  
  691. class DatagramRequestHandler(BaseRequestHandler):
  692.     '''Define self.rfile and self.wfile for datagram sockets.'''
  693.     
  694.     def setup(self):
  695.         
  696.         try:
  697.             StringIO = StringIO
  698.             import cStringIO
  699.         except ImportError:
  700.             StringIO = StringIO
  701.             import StringIO
  702.  
  703.         (self.packet, self.socket) = self.request
  704.         self.rfile = StringIO(self.packet)
  705.         self.wfile = StringIO()
  706.  
  707.     
  708.     def finish(self):
  709.         self.socket.sendto(self.wfile.getvalue(), self.client_address)
  710.  
  711.  
  712.